import cPickle as Pickle
import os,socket,time
from location import Location
from error import *

def load():
    pickle = None
    if os.path.isfile("./miam.pkl"):
        pickle = Pickle.load(open("miam.pkl", 'r'))
    if pickle != None:
        return pickle
    else:
        return (0,{})
    
def save(id,locations):
    Pickle.dump((id,locations), open("miam.pkl", 'w'),True)

def load_preferences(prefs):
    pickle = None
    if os.path.isfile("./settings.pkl"):
        pickle = Pickle.load(open("settings.pkl", 'r'))
    if pickle != None:
        return pickle
    else:
        return get_default_prefs()
    
def save_preferences(prefs):
    Pickle.dump((id,locations), open("miam.pkl", 'w'),True)

def get_current_location(locations):
    """
    Input:Dict of locations
    Output:Return the location
    Dev:Bewiwi
    """
    local_addr = get_local_addr()
    remote_addr = get_remote_addr()
    for location_id in locations:
        params = locations[location_id].param_location
        for param in params:
            for item in params[param]:
                if param == "ipl" and item == local_addr:
                    return locations[location_id]
                elif param == "ipd" and item == remote_ip:
                    return locations[location]
                elif param == "dns":
                    if get_remote_addr_by_name(item) == remote_addr:
                        return locations[location_id]
                
    
def get_remote_addr():
    """Return net ip addr"""
    from urllib2 import urlopen
    try:
        ip =  urlopen("http://www.whatismyip.com/automation/n09230945.asp").read()
    except:    
        return None  
    return ip

def get_local_addr():
    """Return local ip addr"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect(("google.com",80))
    ip = sock.getsockname()[0]
    sock.close() # ? --> useless
    return ip

def get_remote_addr_by_name(hostname):
    import socket 
    ip = socket.gethostbyname(hostname)
    return ip

def get_host_latency(host,port):
    """return remote service latency in ms or an 2-tuple error"""
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.settimeout(1) # set a one second timeout
        start = time.time()
        sock.connect((host,port))
        end = time.time()
        sock.close() # ? --> useless
        return int(( end - start ) * 1000)
    except socket.error, error:
        return error
    
if __name__=="__main__":
   location1 = Location(0)
   location1.name = 'loc1'
   location2 = Location(1)
   location2.name = 'loc2'
   location1.add_param('ipl',"192.168.0.10")
   location2.add_param('dns',"bandoine.hd.free.fr")
   tab={location1.id:location1,location2.id:location2}
   current_location = get_curent_location(tab)
   if current_location != None:
       print current_location.name
   else:
       print 'location not found'
